<template>
  <Modal v-model="isShow" :width="1135" :mask-closable="false" :z-index="10001">
    <p slot="header" >
        <Icon @click="isShow = !isShow" type="ios-information-circle"></Icon>
        <span>相册</span>
    </p>
    <div class="modal-content">
      <div class="left">
        <!-- 添加分类 -->
        <div class="type-title">
          <Poptip placement="right-start" v-model="isVisible">
            <Button @click="clearType" type="primary" size="small" icon="plus-round">添加分类</Button>

            <div slot="content">
              <Form ref="addType" :model="type" :rules="typeValidate" inline>
                <FormItem prop="name">
                    <i-input type="text" clearable v-model="type.name" placeholder="分类名称">
                        <Icon type="compose" slot="prepend"></Icon>
                    </i-input>
                </FormItem>
                <FormItem>
                    <Button type="primary" @click="handleSubmitAddType('addType')" class="ivu-btn-small">添加</Button>
                </FormItem>
            </Form>
            </div>

          </Poptip>
        </div>

        <div class="type-list">

          <div @click="changeCurrIndex(null , -1)" :class="['type-item', currTypeIndex === -1 ? 'active' : '']">
            <div class="type-text">未分组</div>
            <div class="type-os"></div>
          </div>

          <div :class="['type-item', currTypeIndex === i ? 'active' : '']" @click="changeCurrIndex(item, i)" v-for="(item, i) in typeList" :key="item.id">
            <div class="type-text">{{item.name}}</div>
            <div class="type-os" v-show="currTypeIndex === i">
              <Poptip placement="right-start" @on-popper-hide="hidePopper">
                <Icon style="color:#5cadff;" type="md-build"></Icon>
                <div slot="content">
                  <Form ref="editType" :model="type" :rules="typeValidate" inline>
                    <FormItem prop="name">
                        <i-input type="text" clearable v-model="type.name" placeholder="分类名称">
                            <Icon type="compose" slot="prepend"></Icon>
                        </i-input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" size="small" @click="handleSubmitEditType('editType' , i)">提交</Button>
                    </FormItem>
                </Form>
                </div>
              </Poptip>

              <Poptip
                confirm
                @on-popper-hide="hidePopper"
                title="确定要删除吗?"
                @on-ok="deleteType(item, i)">
                <Icon style="color:#ed3f14;padding-left:5px;"  type="ios-close-circle"></Icon>
              </Poptip>

            </div>
          </div>

        </div>
      </div>
      <div class="right">
        <div class="toolBar">
          <!-- del -->
          <Button size="small" @click="batchDelImage" style="float:left;" type="error" icon="information">批量删除</Button>
          <!-- move type -->
          <Dropdown trigger="click" style="margin-left: 20px" @on-click="moveType">
            <Button size="small" type="success" icon="arrow-down-b" style="margin-right: 4px;">移动到</Button>
            <DropdownMenu slot="list" style="text-align:left;">
                <DropdownItem v-for="type in typeList" :key="type.id" :name="type.id">{{type.name}}</DropdownItem>
            </DropdownMenu>
          </Dropdown>
          <!-- upload -->
         <div class="upload-warp">
            <Upload
              multiple
              name="file"
              :data="uploadDate"
              :show-upload-list="false"
              :on-success="uploadSuccess"
              :before-upload="handleUpload"
              :action="action">
              <Button type="primary" size="small" icon="ios-cloud-upload-outline"> 上传</Button>
          </Upload>
         </div>
        </div>

        <div class="img-content">
          <div class="img-item" v-for="(img, i) in imgList" :key="img.id" @click="clickImage(img, i)">
            <div class="img-bg" :style="{backgroundImage: `url(${img.thumb})`}"></div>
            <!--<div class="img-name-bg"></div>-->
            <!--<div class="img-name">{{img.name}}</div>-->
            <div class="img-mask" v-show="img._select">
              <i class="select-index">{{img._index}}</i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="page-warp">
       <Page
          :current="page.current"
          :page-size="page.size"
          :total="page.total"
          show-total
          @on-change="pageChange"></Page>
    </div>
    <div slot="footer">
        <Button type="text"  @click="isShow = !isShow">取消</Button>
        <Button type="primary"  @click="emitSelection"> 选择</Button>
    </div>
    </Modal>
</template>

<script>
import config from '@/config'
import * as upload from '@/api/upload'
import { getToken } from '@/libs/util'
export default {
  naem: 'ImageModal',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 3
    }
  },
  watch: {
    value (val) {
      this.isShow = val
    },
    isShow (val) {
      if (val) {
        this.init()
        this.getImageList()
      } else {
        this.selection = []
      }
      this.$emit('input', val)
    },
    selection (newSelection) {
      let arr = this.imgList
      newSelection.forEach((item, i) => {
        arr = this.imgList.map(img => {
          if (item.id === img.id) {
            img['_index'] = i + 1
          }
          return img
        })
      })
      this.imgList = arr
    },
    type (val) {
      if (this.isQiNiu === 0) {
        this.uploadDate.typeId = val.id
      }
      this.typeId = val.id
    }
  },
  data () {
    return {
      isQiNiu: 0,
      uploadDate: {},
      action: '',
      attachUrl: config.attachUrl,
      token: '',
      isClick: true,
      isShow: false,
      // 加载的图片
      imgList: [],
      // 选择的图片
      selection: [],

      typeList: [],
      typeId: 0,
      // 当前type
      type: {
        id: 0,
        name: ''
      },

      currTypeIndex: -1,

      typeValidate: {
        name: [
          { required: true, message: '分类名称不能为空', trigger: 'blur' },
          { type: 'string', min: 1, max: 16, message: '长度 1~16 个字符', trigger: 'blur' }
        ]
      },

      isVisible: false,
      page: {
        current: 1,
        size: 32,
        total: 0
      },
      loading: false
    }
  },
  methods: {
    // 点击图片
    clickImage (img, i) {
      let flag = !img._select
      img['_select'] = flag
      let index = this.selection.findIndex(item => item.id === img.id)
      flag ? this.selection.push(img) : this.selection.splice(index, 1)
      this.imgList.splice(i, 1, img)
    },
    uploadSuccess (res) {
      console.log(res)
      if (this.isQiNiu === 1) {
        if (res.key) {
          upload.qiniuUpload({ key: res.key, type: this.typeId }).then(result => {
            if (result.code === 1) {
              this.getImageList()
            } else {
              this.$Message.error(result.msg)
            }
          })
        }
      } else {
        if (res.code === 1) {
          this.getImageList()
          // this.$Message.success(res.msg)
        } else {
          this.$Message.error(res.msg)
        }
      }
    },
    // 上传钩子
    handleUpload (file) {
      let token = this.token
      if (!token) {
        this.$Message.error('参数错误！')
        return false
      }
    },

    // 清空 type
    clearType () {
      this.type = {
        id: '',
        name: ''
      }
    },

    // 选中分类
    changeCurrIndex (item, index) {
      this.page.current = 1
      this.currTypeIndex = index
      this.selection = []
      this.type = item ? JSON.parse(JSON.stringify(item)) : { id: 0, name: '' }
      this.getImageList()
    },

    // 提交编辑分类
    handleSubmitEditType (name, i) {
      this.$refs[name][i].validate(async (valid) => {
        if (valid) {
          upload.editType(this.type.id, this.type).then(res => {
            if (res.code === 1) {
              this.typeList.splice(i, 1, res.data)
              this.type = res.data
              this.$Message.success('操作成功！')
            } else {
              this.$Message.error('操作失败！')
            }
          })
        }
      })
    },

    // 提交新增分类
    handleSubmitAddType (name) {
      this.$refs[name].validate(async (valid) => {
        if (valid) {
          upload.addType(this.type).then(res => {
            if (res.code === 1) {
              this.typeList.push(res.data)
              this.isVisible = false
              this.$Message.success('操作成功！')
            } else {
              this.$Message.error('操作失败！')
            }
          })
        }
      })
    },

    // emit selection
    emitSelection () {
      if (!this.selection.length) {
        this.$Message.error({
          content: '请选择图片！',
          duration: 3,
          closable: true
        })
        return
      }
      if (this.selection.length > this.limit) {
        this.$Message.info({
          content: `限制 ${this.limit} 张图片`,
          duration: 3
        })
        return false
      }
      this.$emit('get-selection', JSON.parse(JSON.stringify(this.selection)))
      this.isShow = false
    },

    // 移动图片 改变类型
    moveType (typeId) {
      let len = this.selection.length
      if (!len) {
        this.$Message.info({
          content: '请选择图片！',
          duration: 3,
          closable: true
        })
        return
      }
      let id = this.selection.map(item => item.id)
      id = JSON.stringify(id)
      upload.moveAttachToType({ typeId, id }).then(res => {
        if (res.code === 1) {
          this.selection = []
          this.getImageList()
          this.$Message.success('操作成功！')
        } else {
          this.$Message.error('操作失败！')
        }
      })
    },
    // 删除分类
    deleteType (item, i) {
      upload.delType(item.id).then(res => {
        if (res.code === 1) {
          this.selection = []
          this.changeCurrIndex(null, -1)
          this.typeList.splice(i, 1)
          this.$Message.success('操作成功！')
        } else {
          this.$Message.error('操作失败！')
        }
      })
    },

    // 批量删除图片
    batchDelImage () {
      if (this.selection.length > 0) {
        let s = this.isClick
        this.isClick = false
        if (s) {
          let ids = this.selection.map(item => item.id)
          ids = JSON.stringify(ids)
          upload.delAttach(ids).then(res => {
            this.isClick = true
            if (res.code === 1) {
              this.getImageList()
              this.selection = []
              this.$Message.success('操作成功！')
            } else {
              this.$Message.error('操作失败！')
            }
          })
        }
      } else {
        this.$Message.error('请选择图片')
      }
    },
    init () {
      upload.getType().then(res => {
        if (res.code === 1) {
          this.typeList = res.data
        } else {
          this.$Message.error('操作失败！')
        }
      })
    },
    getImageList () {
      let { id: type } = this.type
      let { current: page, size } = this.page
      upload.attach({ type, page, size }).then(res => {
        if (res.code === 1) {
          this.imgList = res.data.list.map(img => {
            img['_select'] = false
            if (img.save_type === 1) {
              img['thumb'] = this.attachUrl + img.path
            } else {
              img['thumb'] = config.qiniuUrl + img.path
            }
            return img
          })
          this.page.total = res.data.count
        } else {
          this.$Message.error('操作失败！')
        }
      })
    },
    // popper 隐藏钩子
    hidePopper () {
      this.type = {
        id: 0,
        name: ''
      }
    },
    /**
     * 分页
     */
    pageChange (page) {
      this.page.current = page
      this.getImageList()
    },
    /**
     * 每页条数
     */
    // pageSizeChange (size) {
    //   this.page.current = 1
    //   this.page.size = size
    //   this.getImageList()
    // },
    /**
     * 处理分页和条数
     */
    handleParams (params) {
      if (!params.page) this.page.current = 1
      // let data = removeObjectEmptyValue(this.s)
      data.size = this.page.size
      data.page = this.page.current
      return data
    }
  },
  mounted () {
    let _this = this
    upload.getQiniuToken().then(res => {
      if (res.code === 1) {
        if (res.data.isQiNiu === 1) {
          _this.isQiNiu = 1
          _this.token = res.data.token
          _this.uploadDate = {
            token: res.data.token
          }
          _this.action = res.data.action
        } else {
          _this.isQiNiu = 0
          let token = getToken()
          _this.token = token
          _this.uploadDate = {
            Authorization: token,
            typeId: 0
          }
          _this.action = config.attachUrl + 'admin/attach'
        }
      }
    })
  }
}
</script>

<style lang="less" scoped>
.modal-content {
  display: flex;
  height: 500px;
  .left {
    width: 200px;
    border: 1px solid #e9eaec;
    padding: 10px 0;
    border-radius: 5px;
    .type-title {
      padding: 0 0 5px 10px ;
      text-align: left;
      border-bottom: 1px solid #e9eaec;
    }
    .type-list {
      .active {
        background: #e9eaec;
      }
      .type-item {
        display: flex;
        padding: 0 10px;
        line-height: 30px;
        font-size: 12px;
        font-size: 500;
        .type-text {
          width: 150px;
        }
        .type-os {
          width: 50px;
          text-align: right;
        }
        .type-text:hover .type-os{
          display: block;
        }
      }
      .type-item:hover {
          background: #e9eaec;
      }
    }
  }
  .right {
    border: 1px solid #e9eaec;
    margin-left: 10px;
    padding: 10px;
    border-radius: 5px;
    width: 100%;
    .toolBar {
      text-align: right;
      // border-bottom: 1px solid #e9eaec;
      .upload-warp {
        display: inline-block;
        width: 60px;
      }
    }
    .img-content {
      padding: 5px 0;
      .img-item{
        display: inline-block;
        position: relative;
        width: 100px;
        height: 100px;
        margin-right: 10px;
        .img-bg {
          width: 100px;
          height: 100px;
          background-size: cover;
          cursor: pointer;
        }
        .img-mask {
          box-sizing: border-box;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          border: 2px solid #07d;
          .select-index {
            font-size: 12px;
            color: #fff;
            font-style: normal;
            font-family: arial;
            width: 13px;
            text-align: center;
            height: 15px;
            position: absolute;
            z-index: 2;
            right: 0px;
            top: 0px;
          }
        }
        .img-mask::after {
          position: absolute;
          display: block;
          content: " ";
          right: 0;
          top: 0;
          border: 14px solid #07d;
          border-left-color: transparent;
          border-bottom-color: transparent;
          z-index: 1;
        }
        .img-name-bg {
          position: absolute;
          width: 100px;
          height: 25px;
          background: #000;
          bottom: 0;
          left: 0;
          opacity: .3;
        }
        .img-name {
          position: absolute;
          padding-left: 5px;
          width: 100px;
          line-height: 25px;
          font-weight: bold;
          color: #fff;
          bottom: 0;
          left: 0;
          overflow: hidden;
          text-overflow:ellipsis;
          white-space: nowrap;
        }
      }
      .img-item:nth-child(8n) {
        margin: 0
      }
    }
  }
}
</style>
